package com.luo.comm.config.mybatisPlus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.luo.comm.entity.sys.SysUser;
import com.luo.comm.utils.ThreadLocal.ThreadlUser;
import com.luo.comm.vo.BusinessException;
import com.luo.comm.vo.MyResEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动填充字段值的配置
 * 插入时，保存创建时间和创建人，以及更新时间和更新人。
 * 更新时，保存更新时间和更新人。
 * 其中，创建人，更新人都是从ThreadlUser获取的当前线程用户信息
 */

@Component
public class AutoFillFieldValueConfig implements MetaObjectHandler {

    private static final String createdBy = "createdBy";
    private static final String updatedBy = "updatedBy";
    private static final String createdAt = "createdAt";
    private static final String updatedAt = "updatedAt";


    @Override
    public void insertFill(MetaObject metaObject) {

        SysUser loginUser = getLoginUser();
        this.strictInsertFill(metaObject, createdAt, Date.class, new Date());
        this.strictInsertFill(metaObject, createdBy, String.class, loginUser.getUserName());
        this.strictInsertFill(metaObject, updatedAt, Date.class, new Date());
        this.strictInsertFill(metaObject, updatedBy, String.class, loginUser.getUserName());

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        SysUser loginUser = getLoginUser();
        this.strictInsertFill(metaObject, updatedAt, Date.class, new Date());
        this.strictInsertFill(metaObject, updatedBy, String.class, loginUser.getUserName());
    }



    private SysUser getLoginUser (){
        // 获取当前线程的用户信息，检查是否登陆
        SysUser loginUser = ThreadlUser.read();
        if(null== loginUser || StringUtils.isEmpty(loginUser.getUserName()) || StringUtils.isEmpty(loginUser.getRoleId())){
            throw new BusinessException(MyResEnum.USER_NO_LOGIN);
        }
        return loginUser;
    }


}
